<?php
/**
 * Created by PhpStorm.
 * User: 蒙明然
 * Date: 2017/9/26
 * Time: 9:30
 */

namespace app\admin\controller;

use app\common\model\Engineers;
use app\common\model\WorkEquipment;
use app\common\model\WorkOrder;
use app\common\model\Administrative;
use app\common\model\Operation;
use think\db;

class Engineer extends Base
{
    protected static $engineerModel;
    protected $adminModel;
    protected static $workModel;
    // 初始化构造方法，创建模型
    public function __construct()
    {
        parent::__construct();
        // 工程人员模型
        self::$engineerModel = new Engineers();
        // 工单模型
        self::$workModel = new WorkOrder();
        $this->adminModel=new Administrative();
    }

    /**
     * @return mixed|\think\response\Json
     *        渲染 工程人员板块 列表页
     */
    public function index()
    {

        // 接受ajax请求 模糊搜索
        $searchObj = request()->get();

        // 接收当前页码数
        $nowPage = input('get.page') ? input('get.page') : 1;
        // 设置每页显示条数
        $limits = config('pagesize');

        // 判断有没有输入员工编号
        if (!empty($searchObj['engineers_number'])) {
            $where['engineers_number'] = $searchObj['engineers_number'];
        }
        // 判断有没有输入用户名
        if (!empty($searchObj['engineers_name'])) {
            $where['engineers_name'] = $searchObj['engineers_name'];
        }
        // 判断有没有输入手机号
        if (!empty($searchObj['engineers_phone'])) {
            $where['engineers_phone'] = $searchObj['engineers_phone'];
        }
        // 判断有没有输入身份证
        if (!empty($searchObj['engineers_idcard'])) {
            $where['engineers_idcard'] = $searchObj['engineers_idcard'];
        }
        // 判断有没有输入账户状态
        if (!empty($searchObj['engineers_status'])) {
            $where['engineers_status'] = $searchObj['engineers_status'];
        }
        // 查询未被逻辑删除的
        $where['is_delete'] = 0;
        $field = '*';
        // 获取所有工程人员数据
        $data = self::$engineerModel->getAll($where,$field,$nowPage,$limits);

        // 获取工程人员完成工单对应设备数和----------------------
        foreach ($data as $k => $v)
        {
            // 实例化工单表模型,获取完成的工单id
            $workOrderModel = new WorkOrder();
            $workOrderWhere['repair_id'] = $v['engineers_id'];
            $workOrderWhere['work_order_status'] = ['in','10,11,12'];
            $workOrderData = $workOrderModel->getList($workOrderWhere, 'work_order_id') ? $workOrderModel->getList($workOrderWhere, 'work_order_id') : [];
            // 声明一个空数组，装工单id
            $arr = [];
            foreach ($workOrderData as $key => $val){
                array_push($arr,$val['work_order_id']);
            }

            // 实例化工单设备关联表获取设备数总和
            $wkEqModel = new WorkEquipment();
            $wkEqWhere['work_order_id'] = ['in',$arr];
            $data[$k]['equipmentsSum'] = $wkEqModel->getCount($wkEqWhere);

        }

        // 获取数据的总数
        $count = self::$engineerModel->getCount($where);
        // 计算总的页面数
        $allPage = intval(ceil($count / $limits));
        $this->assign('nowPage', $nowPage); //当前页
        $this->assign('allPage', $allPage); //总页数
        // 总的条数
        $this->assign('count',$count);
        $order_id=Db::name('admin_auth_rule')->where(array('title'=>'工单管理','status'=>1))->value('id');
        // 工程人员状态
        $status = config('engineer_status');
        // 循环 获取所有工程人员已完成和未完成的工单
        foreach ($data as $k=>$v){
            $data[$k]['completed'] = self::$workModel->getCompleted($v['engineers_id']);
            $data[$k]['uncompleted'] = self::$workModel->getUncompleted($v['engineers_id']);
            $data[$k]['engineers_status'] = $status[$v['engineers_status']];
            $data[$k]['nowPage'] = $nowPage;
            $data[$k]['allPage'] = $allPage;
            $data[$k]['count'] = $count;
        }

        // 判断用户是否有值
        if (input('get.page')) {
            return json($data);
        }

        // 调用视图 将数据赋值给页面
        return $this->fetch('index',
            [
                'data' => $data,
                'order_id'=>$order_id
            ]);

    }
    //通过运营中心 选择行政区域
    public function getAdmin($id = ''){
        $where['operation']=$id;
        $where['is_delete']=0;
        // 实例化行政区域模型 获取所有行政区域数据
        $Data = Db::name('administrative_info')->where($where)->select();
        return json($Data);
    }

    /**
     * @param string $id
     * @return mixed
     *        渲染 工程人员 详情页面
     */
    public function look($id='')
    {
        // 获取工程人员详情查询的字段
        $field = [
            'a.engineers_name,a.engineers_phone,a.engineers_number,a.engineers_status,
             a.birthday,c.company_name,b.company_name as o_name,a.engineers_address,a.note'
        ];
        // 获取工程人员详情 连表
        $join = [
            ['rq_administrative_info b','b.a_id = a.administrative_id'],    // 行政区域表 对应工程人员表
            ['rq_operation_info c','c.o_id = b.operation']                  // 运营中心表  对应行政区域表
        ];
        // 获取工程人员详情 工程人员id
        $where['a.engineers_id'] = $id;
        // 工程人员详情 主表
        $dbName = 'rq_engineers';
        // 调用getDetail 获取工程人员详情信息
        $data = self::$engineerModel->getDetail($field,$where,$dbName,$join);
        // 调用getCompleted 获取工程人已完成的工单数
        $workCompleted = self::$workModel->getCompleted($id);
        // 调用getUnCompleted 获取工程人员待完成的工单数
        $workUnCompleted = self::$workModel->getUncompleted($id);
        // 调用视图，将数据赋值给页面
        $t=$data['birthday'];
        $data['birthday']=date('Y-m-d',$t);
        return $this->fetch('look',
            [
                'data' => $data,
                'workCompleted' => $workCompleted,
                'workUnCompleted' => $workUnCompleted
            ]);

    }


    /**
     * 编辑
     */
    public function edit($id){
        $operationModel = new Operation();
        $res=self::$engineerModel->getOne(array('engineers_id'=>$id));
        $t=$res['birthday'];
        $res['birthday']=date('Y-m-d',$t);
        $a_id=$res['administrative_id'];
        $adminData=Db::name('administrative_info')->where(array('is_delete'=>0))->select();
        $tem=$this->adminModel->findOne(array('a_id'=>$a_id));
        $o_id=$tem['operation'];
        $operationData = $operationModel->selectOperationInfo();
        $this->assign('operationData',$operationData);
        $this->assign('o_id',$o_id);
        $this->assign('a_id',$a_id);
        $this->assign('adminData',$adminData);
        $this->assign('data',$res);
        return $this->fetch();
    }
    public function doedit()
    {
        $data = request()->post();
        // 判断数据是否为空
        if (empty($data)) {
            return json(['status' => 0, 'message' => '数据有误']);
        }

        foreach ($data as $k => $v) {
            //去掉首位空格
            $data[$k] = trim($v);
        }
        if (empty($data['engineers_name'])) {
            return json(['status' => 0, 'message' => '姓名不能为空！']);
        }
        if (empty($data['birthday'])) {
            return json(['status' => 0, 'message' => '生日不能为空！']);
        }
        if (empty($data['engineers_phone'])) {
            return json(['status' => 0, 'message' => '联系电话不能为空！']);
        }
        if (empty($data['engineers_idcard'])) {
            return json(['status' => 0, 'message' => '身份证号码不能为空！']);
        }
        if (strlen($data['engineers_idcard'])!=18) {
            return json(['status' => 0, 'message' => '身份证号码不足18位！']);
        }
        if (empty($data['administrative_id'])) {
            return json(['status' => 0, 'message' => '行政区域不能为空！']);
        }
        if (empty($data['engineers_address'])) {
            return json(['status' => 0, 'message' => '家庭地址不能为空！']);
        }

        // 判断登录密码
        if (!empty($data['engineers_password'])) {
            $password = setPassword(trim($data['engineers_password']));
            $data['engineers_password'] = $password['password'];
            $data['engineers_slat'] = $password['strict'];
        }

        if(empty($data['engineers_password'])){
            unset($data['engineers_password']);
        }
        $file = request()->file('avatar_img');
        if(!empty($file)){
            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if($info){
                $data['avatar_img'] = $info->getSaveName();
            }else{
                return json(['status' => 0, 'message' => $file->getError()]);
            }
        }
        $data['birthday']=strtotime($data['birthday']);
        // 调用add方法 添加新数据
        $where['engineers_id'] = $data['engineers_id'];
        $result = self::$engineerModel->edit($where, $data);
        // 判断是否添加成功
        if ($result !== 1) {
            return json(['status' => 0, 'message' => '未做任何修改！']);
        } else {
            return json(['status' => 1, 'message' => '更改成功!']);
        }
    }
}